package com.iseastar.guojiang.logic;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;

import com.iseastar.guojiang.MainActivity;
import com.iseastar.guojiang.app.AppCache;
import com.iseastar.guojiang.app.TimerService;
import com.iseastar.guojiang.app.WebViewActivity;
import com.iseastar.guojiang.loc.CourierLocationService;
import com.iseastar.guojiang.model.ServiceTaskBean;
import com.iseastar.guojiang.model.UserBean;
import com.iseastar.guojiang.newcabinet.DealTaskService;
import com.iseastar.guojiang.util.PollingUtils;
import com.shouhuobao.take.model.BannerBean;
import com.shouhuobao.take.utils.StringUtils;

import java.util.ArrayList;

import droid.frame.activity.ActivityMgr;
import droid.frame.utils.http.BitmapUtils;

public class AppLogic {

    /**
     * 检测是否登录 http<br>
     */
    public static boolean checkLogin(final Activity context) {
        UserBean user = AppCache.getUser();
        if (user != null) {
            if (TextUtils.isEmpty(user.getPhone())) {
                // PushService.logout();
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    /**
     * @param url       传入绝对路径
     * @param imageView
     */
    public static void loadImage(final String url, final ImageView imageView) {
        // 默认检查本地缓存
        loadImage(url, imageView, true);
    }

    /**
     * @param url          传入绝对路径
     * @param isCheckLocal 是否检查本地缓存
     * @param imageView
     */
    public static void loadImage(final String url, final ImageView imageView, final boolean isCheckLocal) {
        if (imageView == null) {
            Log.w("app:logic", "imageview为空, url不予请求");
            return;
        }
        // 头像
        new AsyncTask<Void, Void, Bitmap>() {
            @Override
            protected Bitmap doInBackground(Void... params) {
                // 头像
                Bitmap image = BitmapUtils.loadBitmapFromNet(url, isCheckLocal);
                return image;
            }

            @Override
            protected void onPostExecute(Bitmap result) {
                if (result != null && imageView != null) {
                    imageView.setImageBitmap(result);
                }
            }
        }.execute();
    }

    /**
     * 支付成功界面跳转
     */
    public static void onPaySuccess(Activity context) {
        //这里不建议用增强for循环，之前使用增强for，发现栈里的没有清除干净，所以这里采用普通的倒序移除，符合栈的先进后出原理
        if (ActivityMgr.getAllActivitys() != null && ActivityMgr.getAllActivitys().size() > 0) {
            for (int i = ActivityMgr.getAllActivitys().size() - 1; i > 0; i--) {
                Activity activity = ActivityMgr.getAllActivitys().get(i);
                if (ActivityMgr.getAllActivitys().size() != 1) {
                    droid.frame.utils.android.Log.d("11111", activity);
                    activity.finish();
                    ActivityMgr.remove(activity);
                }
            }
        }
        Intent intent = new Intent();
        if (AppCache.getUser().isYiZhan()) {
            intent.setClass(context, com.shouhuobao.take.MainActivity.class);
        } else {
            intent.setClass(context, MainActivity.class);
        }
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        // intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        // intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        Bundle bundle = new Bundle();
        bundle.putString("orderId", AppCache.getOrderId() + "");
        bundle.putString("userId", AppCache.getUser().getId() + "");
        bundle.putSerializable("order", AppCache.getOrder());
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

    /**
     * 处理banner数据跳转
     *
     * @param bannerBean
     */
    public static void disposeBannerData(Activity context, BannerBean bannerBean) {
        if (1 == bannerBean.getOpenType()) {
            if (!StringUtils.isEmpty(bannerBean.getLink())) {
                Intent intent = new Intent();
                intent.setClass(context, WebViewActivity.class);
                intent.putExtra("title", bannerBean.getTitle());
                intent.putExtra("url", bannerBean.getLink());
                context.startActivity(intent);
            }
        } else {
            if (!StringUtils.isEmpty(bannerBean.getLink())) {
                String activityName = bannerBean.getLink().split(";")[0];
                if (!StringUtils.isEmpty(activityName)) {
                    contextToActive(context, activityName);
                }
            }
        }

        //        if (mBanner.getBannerBeanList().size() == 1) {
        //            if (position == 0) {
        //                getActivityContext().startActivity(new Intent(getActivityContext(), StationInviteActivity.class));
        //            }
        //        } else {
        //            if (position == 0) {
        //                AppLogic.contextToActive(getActivityContext());
        //            } else if (position == 1) {
        //                getActivityContext().startActivity(new Intent(getActivityContext(), StationInviteActivity.class));
        //            }
        //        }
    }

    /**
     * 判断榜单发布日期，跳转到活动页
     */
    public static void contextToActive(Activity context, String activityName) {
        try {
            //            String date = "2017.10.02";
            //            String currentDate = DateUtils.getDateFormat().format(new Date());
            //            //当前时间小于10.02
            //            if (DateUtils.getDateFormat().parse(date).getTime() > DateUtils.getDateFormat().parse(currentDate).getTime()) {
            //                Intent intent = new Intent(context, WebViewActivity.class);
            //                intent.putExtra("title","榜单活动预热公告");
            //                context.startActivity(intent);
            //            } else {
            AppHttp.getInstance().queryActiveConfig();
            Intent intent = new Intent();
            intent.setClassName(context, activityName);
            context.startActivity(intent);
            //            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param diff 时间差、单位毫秒
     * @return 返回 [时、分、秒]
     */
    public static long[] timeDiff(long diff) {
        long diffSeconds = diff / 1000 % 60;
        long diffMinutes = diff / (60 * 1000) % 60;
        long diffHours = diff / (60 * 60 * 1000) % 24;
        // long diffDays = diff / (24 * 60 * 60 * 1000);
        droid.frame.utils.android.Log.d("diff", diffSeconds);
        return new long[]{diffHours, diffMinutes, diffSeconds};
    }

    /**
     * @param diff 时间差、单位毫秒
     * @return 返回 [天、时、分、秒]
     */
    public static long[] timeDiffDHMS(long diff) {
        long diffSeconds = diff / 1000 % 60;
        long diffMinutes = diff / (60 * 1000) % 60;
        long diffHours = diff / (60 * 60 * 1000) % 24;
        long diffDays = diff / (24 * 60 * 60 * 1000);
        droid.frame.utils.android.Log.d("diff", diffSeconds);
        return new long[]{diffDays, diffHours, diffMinutes, diffSeconds};
    }

    /**
     * 参考{@link #timeDiff(long)} 时分秒-字符串格式化为两位数
     *
     * @param diff
     * @return
     */
    public static String[] timeDiffStr(long diff) {
        long[] diffs = timeDiff(diff);
        String[] arr = new String[diffs.length];
        for (int i = 0; i < diffs.length; i++) {
            if (String.valueOf(diffs[i]).length() < 2) {
                arr[i] = "0" + diffs[i];
            } else {
                arr[i] = "" + diffs[i];
            }
        }
        return arr;
    }

    /**
     * 参考{@link #timeDiff(long)} 日时分秒-字符串格式化为两位数
     *
     * @param diff
     * @return
     */
    public static String[] timeDiffDHMSStr(long diff) {
        long[] diffs = timeDiffDHMS(diff);
        String[] arr = new String[diffs.length];
        for (int i = 0; i < diffs.length; i++) {
            if (String.valueOf(diffs[i]).length() < 2) {
                arr[i] = "0" + diffs[i];
            } else {
                arr[i] = "" + diffs[i];
            }
        }
        return arr;
    }

    /**
     * 用于存储弹出passport的对象
     */
    private static ArrayList<ServiceTaskBean> passportList = new ArrayList<ServiceTaskBean>();

    public static boolean isEmptyForList() {
        if (passportList.size() == 0) {
            return true;
        } else {
            return false;
        }
    }

    public static synchronized ArrayList<ServiceTaskBean> getPassportList() {
        return passportList;
    }

    //用于应用进入后台的操作的数据源
    private static ArrayList<ServiceTaskBean> appBackgroundPassportList = new ArrayList<>();

    public static synchronized ArrayList<ServiceTaskBean> getAppBackgroundPassportList() {
        return appBackgroundPassportList;
    }

    public static void courierBackToHomeAndRefresh(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        Bundle bundle = new Bundle();
        bundle.putBoolean("taskexception", true);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

    public static void logoutDealService(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, CourierLocationService.class);
        intent.setPackage(context.getPackageName());
        intent.putExtra("msgId", com.iseastar.guojiang.consts.MsgID.courier_location_upload_data);
        context.stopService(intent);
        Intent intent1 = new Intent();
        intent1.setClass(context, DealTaskService.class);
        intent1.setPackage(context.getPackageName());
        intent1.putExtra("isStop", false);
        context.stopService(intent1);
        PollingUtils.stopPollingService(context, TimerService.class, TimerService.ACTION);
    }
}
